<template>
    <el-card shadow="never" :body-style="{ padding: '20px 20px 20px 20px' }">
        <el-tabs>
            <el-tab-pane label="基本设置">
                <el-form ref="account" :model="account" label-width="100px" :rules="rules">
                  <!-- <el-form-item v-if="account.roles" label="角色:">
                        <el-input  v-if="account.roles" v-model="account.roles[0].name"></el-input>
                    </el-form-item> -->
                    <el-form-item label="用户名:" prop ="name">
                        <el-input v-model="account.name"></el-input>
                    </el-form-item>
                    <el-form-item label="昵称:">
                        <el-input v-model="account.nickname"></el-input>
                    </el-form-item>
                    <el-form-item label="年龄:" >
                        <el-input-number type="text" :min="1"  v-model="account.age"></el-input-number>
                    </el-form-item>
                    <el-form-item label="手机号码:" prop="phone">
                        <el-input v-model="account.phone"></el-input>
                    </el-form-item>
                    <el-form-item label="电子邮件:" prop ="email">
                        <el-input v-model="account.email"></el-input>
                    </el-form-item>
                    <el-form-item label="性别:">
                        <el-radio-group v-model="account.gender">
                            <el-radio :label="1">男</el-radio>
                            <el-radio :label="2">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="出生日期:">
                        <el-date-picker align="right" v-model="account.birthDate" type="date" placeholder="选择出生日期" :picker-options="$store.state.datePickerOptions" style="width: 100%;"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="备注信息:">
                        <el-input type='textarea' v-model="account.summary" auto-complete='off' rows="4" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="头像设置:">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/accounts/upload/"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                            >
                            <img  v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="update('account')">更新</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="修改密码">
                <el-form ref="password" :model="password" label-width="80px" :rules="rules2">
                    <el-form-item label="原密码" prop="oldPass">
                        <el-input type="password" v-model="password.oldPass"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="password">
                        <el-input type="password" v-model="password.password"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="checkPass">
                        <el-input type="password" v-model="password.checkPass"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="updatePwd('password')">确认修改</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>
    </el-card>
</template>
<style>
     .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
</style>
<script>
export default {
  name: "Profile",
  data() {
      var validateName = (rule,value,callback) => {
        if(typeof(value) == "undefined" || value == ""){
          callback(new Error('请输入用户名'));
        }else{
            if(this.account.name == this.userName)
            {
                callback()
            }else{
            this.$http.get("/api/accounts/",{params:{'name':this.account.name}}).then(res => {
          if(res.data.content.length == 0){
            callback();
          }else{
            callback(new Error('该用户名已被注册'));
          }
        })
        }
        }
      };
      var validatePhone = (rule,value,callback) => {
        if(typeof(value) == "undefined" || value == ""){
          callback(new Error('请输入手机号'));
        }else{
            var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
            if(!myreg.test(value)){
                callback(new Error('手机号格式不正确'));
            }else{
                callback();
            }
        }
      };
      var validateEmail = (rule,value,callback) => {
          if(typeof(value) == "undefined" || value == "")
          {
              callback(new Error)
          }else{
              var myreg=/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
              if(!myreg.test(value)){
                  callback(new Error('邮箱格式不正确'));
              }else{
                  callback();
              }
          }
      };
      var validatePass = (rule, value, callback) => {
        if (value === ''|| typeof(value) == "undefined") {
          callback(new Error('请输入新密码'));
        } else {
          if (this.password.checkPass !== '') {
            this.$refs.password.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '' || typeof(value) == "undefined") {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.password.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
    return {
      userId : this.$store.state.userId ,
      imageUrl:'',
      account:{content: []},
      password:{},
      userName: '',
      pic:'',
      rules:{
        name:[{ required:true, validator: validateName, trigger: 'blur'}],
        email:[{required:true, validator: validateEmail,trigger:'blur'}],
        phone:[{required:true, validator: validatePhone, trigger:'blur'}],
        nickName:[{required:true, message: '昵称不能为空',trigger:'blur'}]
      },
      rules2:{
          oldPass:[{required:true, message:'原密码不能为空',trigger: 'blur'}],
          password:[{required:true,validator:validatePass,trigger:'blur'}],
          checkPass:[{required:true,validator:validatePass2,trigger:'blur'}]
      }
      
    };
  },
  mounted() {
      this.init();
  },
  methods: {
      init(){
          this.$http.get(`/api/accounts/${this.userId}`).then(res => {
              this.userName = res.data.name;
              this.account = res.data;
              this.imageUrl = this.$store.state.pic;     
              this.account.content.roles[0].name = this.roleName;
          })
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024  < 64;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 64K!');
        }
        return isJPG && isLt2M;
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        if(res)
        {
            this.pic = res;
        }
      }
      ,
      update(account)
      {
          this.$refs[account].validate((valid) => {
              if(valid)
              {
                  // this.account.roles = {};
                  console.info(this.account);
                  this.account.pic = this.pic;
                  this.$http.put('/api/accounts/'+this.userId,this.account).then(res => {
                      this.init();
                      this.$notify({type:'success',title:'更新成功',message:'信息更新成功'}) ;
                      this.$store.commit("setPic", 'data:image/png;base64,'+this.pic);
                      this.$store.commit("setUserNickName", this.account.nickname);
                  })
              }
          })
      },
      updatePwd(password)
      {
          this.$refs[password].validate((valid) => {
              if(valid)
              {
                  this.$http.get('/api/accounts/'+this.userId+'/password',{params:{"oldPass":this.password.oldPass,"newPass":this.password.checkPass}}).then(res => {
                      if(res.data.success == false){
                          this.$notify({type:'error',title:'修改失败',message:'原始密码错误'});
                      }else{
                        this.$notify({type:'success',title:'修改成功',message:'密码修改成功'});
                        this.$router.push({ path: "/system/profile" });
                      }
                  })
              }
          })
      }
  }
};
</script>
